import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home'
import { isLogin } from 'utils/login'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      needLogin: false
    }
  },
  {
    path: '/mine',
    name: 'mine',
    component: () => import('views/Mine'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/Cart',
    name: 'Cart',
    component: () => import('views/Cart'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/Detail',
    name: 'Detail',
    component: () => import('views/Detail'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('views/order'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('views/login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/addressAdd',
    name: 'addressAdd',
    component: () => import('views/addressAdd'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/addressList',
    name: 'addressList',
    component: () => import('views/addressList'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/addressEdit',
    name: 'addressEdit',
    component: () => import('views/addressEdit'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('views/search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/itemsList/:cate_id',
    name: 'itemsList',
    component: () => import('views/itemsList'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchList',
    name: 'searchList',
    component: () => import('views/searchList'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/sorts',
    name: 'sorts',
    component: () => import('views/sorts'),
    meta: {
      needLogin: false
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  // 判断目标路由是否需要登录
  if (to.meta.needLogin) {
    if (isLogin()) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: to.fullpath
        }
      })
    }
  } else {
    next()
  }
})
export default router
